﻿Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Configuration
Imports System.Xml
Imports System.Net
Imports System.Collections
Imports System.Collections.Generic
Imports System.IO
Imports System.Data

Partial Class ActivityTypeUpload
    Inherits System.Web.UI.Page
    Dim sharePointListPath As String = ConfigurationManager.AppSettings("SharePointServer")
    Dim lock As Boolean
    Public scripttext As String
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        AddHandler SaveDocument.Click, AddressOf Me.SaveDocument_Click

        If Not Page.IsPostBack Then
            Dim ID As String = Request("ID")
            Dim Type As String = Request("Type")
            Dim PlanYear As String = Val(Request("PlanYear"))
            If Type = "Cmmts" Then
                Dim adapter As New MasterDataSet2TableAdapters.CmmtsTableAdapter
                Dim dtTable As New MasterDataSet2.CmmtsDataTable

                Dim sql As String = "select * from Cmmts "
                'sql += " inner join BudgetDetails on BudgetDetails.Cmmt_CmmtCode = Cmmts.CmmtCode "
                'sql += " and BudgetDetails.Cmmt_PlanYear = Cmmts.PlanYear "
                sql += " WHERE Cmmts.CmmtCode =  '" & ID & "' "
                sql += " AND Cmmts.PlanYear =  '" & PlanYear & "' "
                adapter.SearchCmmts(dtTable, sql)
                If dtTable.Rows.Count > 0 Then
                    Title.Text = dtTable.Rows(0)("FileNamePattern").ToString()
                    'hddBudgetDetails_id.Value = dtTable.Rows(0)("BudgetDetails_id").ToString()
                End If
            Else
                Dim adapter As New MasterDataSetTableAdapters.ActivityTypesTableAdapter
                Dim dtTable As New MasterDataSet.ActivityTypesDataTable

                Dim sql As String = "select * from activityTypes "
                'sql += " inner join [BudgetDetails] on activityTypes.CmmtItem_CmmtCode = [BudgetDetails].[Cmmt_CmmtCode]  "
                'sql += " and activityTypes.PlanYear = [BudgetDetails].PlanYear "
                sql += " WHERE activityTypes.ActivityTypeCode =  '" & ID & "' "
                sql += " AND activityTypes.PlanYear =  '" & PlanYear & "' "
                adapter.SearchActType(dtTable, sql)
                If dtTable.Rows.Count > 0 Then
                    Title.Text = dtTable.Rows(0)("FileNamePattern").ToString()
                    'hddBudgetDetails_id.Value = dtTable.Rows(0)("BudgetDetails_id").ToString()
                End If
            End If
            BindGridViewData()
        End If
    End Sub

    Protected Sub SaveDocument_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim docinfo As New System.IO.DirectoryInfo(Server.MapPath("~\Template\"))
        If Not docinfo.Exists Then
            docinfo.Create()
        End If

        Dim saveDir As String = "\Template\"
        Dim appPath As String = Request.PhysicalApplicationPath

        If (DocumentFile.HasFile) Then
            Dim extension As String = System.IO.Path.GetExtension(DocumentFile.FileName)
            'Dim fileName As String = GenerateFileName("yyyyMMddhhmmss") & "-" & Session("users") & extension

            Dim fileSize As Integer = DocumentFile.ContentLength
            Dim mimeType As String = DocumentFile.ContentType

            If (fileSize > 5242880) Then
                filelimit.Visible = True
                Exit Sub
            Else
                filelimit.Visible = False
            End If

            'Dim savePath As String = appPath + saveDir + fileName

            Dim fileName As String = System.IO.Path.GetFileName(DocumentFile.FileName)

            'Add By Orn 28/06/2558
            Try
                If fileName.Length > 20 Then
                    Throw New Exception("ชื่อไฟล์เกิน 20 ตัวอักษร กรุณาเปลี่ยนชื่อใหม่")
                Else
                    DocumentFile.MoveTo(Server.MapPath("~\Template\") & fileName, Brettle.Web.NeatUpload.MoveToOptions.Overwrite)
                    UploadFileToSharePoint(Server.MapPath("~\Template\") & fileName, sharePointListPath + fileName)
                    Try
                        File.Delete(Server.MapPath("~\Template\") & fileName)
                    Catch ex As Exception

                    End Try

                    '''' End Sharepoint Upload

                    ''Dim mySelectQuery As String
                    ''Dim ProjectID As String
                    'Dim EformID As Decimal
                    'EformID = Val(hddBudgetDetails_id.Value)
                    'Dim adapter1 As New AttachmentTableAdapters.AttachmentsTableAdapter
                    'Dim adapter2 As New AttachmentTableAdapters.BudgetDetailsTableAdapter
                    'Dim item_no As Integer
                    'item_no = adapter1.GetMaxItemNo(EformID)
                    ''adapter1.InsertAttachment(item_no, fileName, extension, fileSize, mimeType, Now(), Nothing, Session("usr_id"), Nothing, EformID, 0, Title.Text)
                    'Dim currentAmount As Decimal = adapter1.GetAttAmount(EformID)
                    ''adapter2.UpdateAttAmount(currentAmount, EformID)
                    Try
                        If Request("Type") = "Cmmts" Then
                            Dim adapter As New MasterDataSetTableAdapters.CmmtsTableAdapter
                            Dim dtCmmts As New MasterDataSet.CmmtsDataTable
                            dtCmmts = adapter.GetDataByCode(Val(Request("PlanYear")), Request("ID"))
                            Dim template As String = ""
                            If dtCmmts.Rows.Count > 0 Then
                                template = dtCmmts(0)("TemplateName").ToString()
                            End If
                            If template = "" Then
                                adapter.UpdateFile(Session("usr_id"), Title.Text, fileName, Request("ID"), Val(Request("PlanYear")))
                            Else
                                Throw New Exception("มีการ Upload file แล้ว กรุณาลบ file เก่าและ Upload ใหม่")
                            End If

                        Else
                            Dim adapter As New MasterDataSetTableAdapters.ActivityTypesTableAdapter
                            Dim dtActivityTypes As New MasterDataSet.ActivityTypesDataTable
                            dtActivityTypes = adapter.GetDataByCode(Request("ID"), Val(Request("PlanYear")))
                            Dim template As String = ""
                            If dtActivityTypes.Rows.Count > 0 Then
                                template = dtActivityTypes(0)("TemplateName").ToString()
                            End If
                            If template = "" Then
                                adapter.UpdateFile(Session("usr_id"), Title.Text, fileName, Request("ID"), Val(Request("PlanYear")))
                            Else
                                Throw New Exception("มีการ Upload file แล้ว กรุณาลบ file เก่าและ Upload ใหม่")
                            End If
                        End If
                        BindGridViewData()
                        Title.Text = ""
                        'If Request("fid") = "f05" Then
                        scripttext = "<script>alert('Upload success.');window.close();</script>"
                        'End If
                    Catch ex As Exception
                        scripttext = "<script>alert('" & ex.Message & "');window.close();</script>"
                    End Try
                End If
            Catch ex As Exception
                scripttext = "<script>alert('" & ex.Message & "');window.close();</script>"
            End Try

            
            

            
        End If
    End Sub
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        Dim RunningNo As Label = e.Row.Cells(0).FindControl("RunningNo")
        If Not (RunningNo Is Nothing) Then
            RunningNo.Text = e.Row.RowIndex + 1
        End If

        If lock = True Then
            e.Row.Cells(e.Row.Cells.Count - 1).Text = ""
        End If
    End Sub

    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        GridView1.EditIndex = -1
        BindGridViewData()
    End Sub
    Protected Sub DeleteDocument_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ConfirmResult As Boolean = ConfirmBox.Value
        If ConfirmResult = False Then
            Exit Sub
        End If

        Dim Row As System.Web.UI.WebControls.GridViewRow
        Row = sender.Parent.Parent
        Dim IDX As Label = Row.Cells(3).FindControl("ProjectDocumentID")
        Dim adapter As New AttachmentTableAdapters.AttachmentsTableAdapter
        Dim adapter2 As New AttachmentTableAdapters.BudgetDetailsTableAdapter

        'adapter.DeleteAttachment(Val(IDX.Text))
        Dim filename As Label = Row.Cells(3).FindControl("Filename")
        Dim countfile As Integer = 0
        'countfile = adapter.CountExistFile(filename.Text.Trim)

        'Dim currentAmount As Decimal = adapter.GetAttAmount(Val(hddBudgetDetails_id.Value))

        'adapter2.UpdateAttAmount(currentAmount, Val(hddBudgetDetails_id.Value))
        'If Request("fid") = "f05" Then
        '    scripttext = "<script>F05_close(" & currentAmount & "," & Request("rownum") & ");</script>"
        'End If
        If Request("Type") = "Cmmts" Then
            Dim adapterUpdate As New MasterDataSetTableAdapters.CmmtsTableAdapter
            countfile = adapterUpdate.UpdateTemplate(Request("ID"), Val(Request("PlanYear")))
        Else
            Dim adapterUpdate As New MasterDataSetTableAdapters.ActivityTypesTableAdapter
            countfile = adapterUpdate.UpdateTemplate(Request("ID"), Val(Request("PlanYear")))
        End If
        BindGridViewData()

        If filename.Text.Trim <> "" And countfile > 0 Then
            DeleteFileSP(sharePointListPath & filename.Text.Trim)
        End If
        'scripttext = "<script>window.close();</script>"

    End Sub
    Sub BindGridViewData()
        'Dim adapter As New AttachmentTableAdapters.AttachmentsTableAdapter
        'Dim data As New Attachment.AttachmentsDataTable
        'data = adapter.GetDataByRefID(Val(hddBudgetDetails_id.Value))
        If Request("Type") = "Cmmts" Then
            Dim adapterUpdate As New MasterDataSetTableAdapters.CmmtsTableAdapter
            Dim dtCmmts As New MasterDataSet.CmmtsDataTable
            dtCmmts = adapterUpdate.GetDataByFileType(Request("ID"), Val(Request("PlanYear")))
            If Not IsNothing(dtCmmts) And dtCmmts.Rows.Count > 0 Then
                If dtCmmts(0)("TemplateName").ToString() = "" Then
                    dtCmmts = Nothing
                End If
            End If
            GridView1.DataSource = dtCmmts
            GridView1.DataBind()
        Else
            Dim adapterUpdate As New MasterDataSetTableAdapters.ActivityTypesTableAdapter
            Dim dtActivityTypes As New MasterDataSet.ActivityTypesDataTable
            dtActivityTypes = adapterUpdate.GetDataByFileType(Request("ID"), Val(Request("PlanYear")))
            If Not IsNothing(dtActivityTypes) And dtActivityTypes.Rows.Count > 0 Then
                If dtActivityTypes(0)("TemplateName").ToString() = "" Then
                    dtActivityTypes = Nothing
                End If
            End If
            GridView1.DataSource = dtActivityTypes
            GridView1.DataBind()
        End If
        
    End Sub
    Public Function GenerateOnClick(ByVal data As Object) As String
        If Not IsDBNull(data) Then
            Return "window.open('DownloadFile.aspx?filepath=" & data & "&filename=" & data & "','view_document','menubar=0,resizable=1,width=800,height=600');"
        Else
            Return ""
        End If
    End Function
    'Public Shared Function GenerateFileName(ByVal data As String) As String
    '    Return Now().ToString(data)
    'End Function

    Sub UploadFileToSharePoint(ByVal TemplateFilePath As String, ByVal SharePointPath As String)

        Dim resp As WebResponse = Nothing

        Try
            ' Create a PUT Web request to upload the file.
            Dim request As WebRequest = WebRequest.Create(SharePointPath)
            'Dim mycache As New CredentialCache
            'mycache.Add(New Uri(SharePointPath), "Windows", New NetworkCredential("WIN-MUDL4FHR3S1\Administrator", "Secret1"))
            request.Credentials = CredentialCache.DefaultCredentials
            request.Method = "PUT"

            ' Allocate a 1 KB buffer to transfer the file contents.
            ' You can adjust the buffer size as needed, depending on
            ' the number and size of files being Template.
            Dim buffer() As Byte = New Byte(1023) {}

            ' Write the contents of the local file to the
            ' request stream.
            Using stream As Stream = request.GetRequestStream()
                Using fsWorkbook As FileStream = _
                    File.Open(TemplateFilePath, _
                        FileMode.Open, FileAccess.Read)
                    Dim i As Integer = fsWorkbook.Read(buffer, 0, _
                        buffer.Length)

                    Do While i > 0
                        stream.Write(buffer, 0, i)
                        i = fsWorkbook.Read(buffer, 0, buffer.Length)
                    Loop

                End Using
            End Using

            ' Make the PUT request.

            'Response.Write(resp.ResponseUri.AbsolutePath.ToString())
            resp = request.GetResponse()

        Catch ex As Exception
            Throw ex
        Finally
            'Response.Write(resp.ResponseUri.AbsolutePath.ToString())
            'resp.Close()
        End Try

    End Sub

    Sub DeleteFileSP(ByVal SharePointPath As String)
        Dim resp As WebResponse = Nothing

        Dim request As WebRequest = WebRequest.Create(SharePointPath)
        request.Credentials = CredentialCache.DefaultCredentials
        request.Method = "DELETE"
        resp = request.GetResponse()
    End Sub
End Class
